﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OrganizationName.Common;

namespace OrganizationName.DynamicData
{
    public abstract class _ID : Tree<_ID>
    {
        public int ID { get; set; }

        public override string UniqueId
        {
            get
            {
                return "@ID" + base.UniqueId;
            }
        }

        public virtual string InsertID
        {
            get
            {
                return ID == 0 ? UniqueId : ID.ToString();
            }
        }


        public virtual string GetInsertScript()
        {
            StringBuilder insertScriptBuilder = new StringBuilder();
            GenerateInsertScript(insertScriptBuilder);
            return insertScriptBuilder.ToString();
        }

        protected abstract string InsertScriptFieldList { get; }
        protected abstract string InsertScriptValueList { get; }

        private const string INSERT_SCRIPT = "DECLARE {0} INT\r\nINSERT INTO [{1}] ([Root], [Parent], {2}) VALUES ({3}, {4}, {5})\r\nSET {0} = SCOPE_IDENTITY()\r\n\r\n";

        public virtual void GenerateInsertScript(StringBuilder insertScriptBuilder)
        {
            if (ID == 0)
            {
                insertScriptBuilder.AppendFormat
                (
                    INSERT_SCRIPT,
                    UniqueId,
                    GetType().Name,
                    InsertScriptFieldList,
                    Root != null ? (this != Root ? Root.InsertID : "0") : "0",
                    Parent != null ? Parent.InsertID : "0",
                    InsertScriptValueList
                );
            }

            if (Children != null)
            {
                foreach (_ID childSchema in Children)
                {
                    insertScriptBuilder.AppendFormat("{0}", childSchema.GetInsertScript());
                }
            }
        }

    }
}
